package com.dswfort.novelSpider

import org.jsoup.Jsoup
import java.net.URI

/**
 * 笔下文学网小说解析
 */
class BxwxDownloader : BaseNovelDownloader("https://www.7bxwx.com") {

    /**
     * 解析章节清单
     * @param novelUrl 小说地址
     * @return 小说信息
     */
    override fun parseChapters(novelUrl: String): Novel {
        val uri = URI(novelUrl)
        val doc = Jsoup.connect(novelUrl).timeout(30000).get()
        val bookInfoElement = doc.body().select("div[id=maininfo]")
        val title = bookInfoElement.select("h1").text()
        val author = bookInfoElement.select("a")[0].text()
        val introduceElement = bookInfoElement.select("div[id=intro]")
        val introduce = introduceElement.text()

        val chapters = ArrayList<Chapter>()
        val chaptersElement = doc.body().select("div[class=box_con] div[id=list] dl")
        val chapterElements = chaptersElement[0].select("dd, dt")
        var chapterBeginIndex = -1
        chapterElements.withIndex().forEach { (index, chapterElement) ->
            if (chapterBeginIndex < 0) {
                if (chapterElement.select("b").text().endsWith(("正文"))) {
                    chapterBeginIndex = index
                }
            } else {
                val chapterUrl = "${uri.scheme}://${host}${chapterElement.select("a").attr("href")}"
                val chapter = Chapter(chapterElement.text(), chapterUrl)
                chapters.add(chapter)
            }
        }

        return Novel(title, author, introduce, chapters, novelUrl)
    }

    /**
     * 解析小说章节
     * @param chapter 章节信息
     * @return 章节内容
     */
    override fun parseChapter(chapter: Chapter): String {
        val chapterTitle = chapter.title
        val txt = StringBuilder()
        var pbNext: String
        var pbNextUrl = chapter.url
        val uri = URI(pbNextUrl)

        do {
            val doc = Jsoup.connect(pbNextUrl).timeout(30000).get()

            val txtElements = doc.body().select("div[id=content]").select("p")
            txtElements.forEach {
                val row = it.text()
                if (!row.contains("这章没有结束^.^，请点击下一页继续阅读！") && !row.contains("这个章节后面还有哦") && !row.contains("笔下文学更新速度全网最快")) {
                    if (txt.isNotEmpty()) {
                        txt.append(newline)
                    }

                    txt.append(row)
                }
            }

            // 下一章/下一页
            val pbNextElement = doc.body().select("div[class=bottem2] a[id=A3]")
            pbNext = pbNextElement.text()
            pbNextUrl = "${uri.scheme}://${host}${pbNextElement.attr("href")}"
        } while ("下一页" == pbNext)

        return "${chapterTitle}$newline$txt"
    }
}